
package de.fhhof.brst.event;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import de.fhhof.brst.dao.EventDAO;
import de.fhhof.brst.dao.HibernateEventDAO;
import de.fhhof.brst.data.Booking;
import de.fhhof.brst.data.Event;
import de.fhhof.brst.data.User;
import de.fhhof.brst.session.SessionBean;
@ManagedBean
@RequestScoped
public class Bookings implements Serializable {
  /**
   * 
   */
  private static final long serialVersionUID =  7322993517662841609L;

  private List<de.fhhof.brst.data.Event> bookings =  new ArrayList<Event>();

  private de.fhhof.brst.dao.EventDAO eventDAO =  HibernateEventDAO.getHibernateEventDAO();

  @ManagedProperty(value = "#{sessionBean}")
  private de.fhhof.brst.session.SessionBean sessionBean;

  private de.fhhof.brst.data.Event[] selectedBookings;

  private List<de.fhhof.brst.data.Booking> tempBookings;

  public Bookings() {
  }

  @PostConstruct
  private void fillBookingsList() {
		tempBookings = eventDAO.getBookings(sessionBean.getUser().getId());
		Event event;
		
		for (Booking booking : tempBookings) {
			event = eventDAO.getEvent(booking.getEvent_id());
			bookings.add(event);
		}
  }

  private List<de.fhhof.brst.data.Booking> fillDeleteBookingList() {
		List<Booking> deleteBookings = new ArrayList<Booking>();
		for(Event event : selectedBookings) {
			for(Booking booking : tempBookings) {
				if(event.getId() == booking.getEvent_id()) {
					deleteBookings.add(booking);
					tempBookings.remove(booking);
					break;
				}
			}
		}
		
		return deleteBookings;
  }

  public void setSessionBean(de.fhhof.brst.session.SessionBean sessionBean) {
		this.sessionBean = sessionBean;
  }

  public String delete() {
		for(Booking deleteBooking : this.fillDeleteBookingList()) {
			eventDAO.deleteBooking(deleteBooking);
		}
		
		return "/user_bookings_frame.xhtml?faces-redirect=true";
  }

  public List<de.fhhof.brst.data.Event> getBookings() {
		return bookings;
  }

  public void setBookings(List<Event> bookings) {
		this.bookings = bookings;
  }

  public de.fhhof.brst.dao.EventDAO getEventDAO() {
		return eventDAO;
  }

  public void setEventDAO(de.fhhof.brst.dao.EventDAO eventDAO) {
		this.eventDAO = eventDAO;
  }

  public de.fhhof.brst.data.Event[] getSelectedBookings() {
		return selectedBookings;
  }

  public void setSelectedBookings(de.fhhof.brst.data.Event[] selectedBookings) {
		this.selectedBookings = selectedBookings;
  }

  public de.fhhof.brst.session.SessionBean getSessionBean() {
		return sessionBean;
  }

}
